package li.nibble.twittertido.adapter;

import java.util.ArrayList;

import li.nibble.twittertido.R;
import li.nibble.twittertido.beans.User;
import li.nibble.twittertido.lazyimage.ImageLoader;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class UserAdapter extends ArrayAdapter<User> {

	ArrayList<User> users;
	LayoutInflater vi;
	ImageLoader imageLoader;

	public UserAdapter(Context context, int textViewResourceId,
			ArrayList<User> objects) {
		super(context, textViewResourceId, objects);
		this.users = objects;
		vi = (LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(context);
	}

	public static class ViewHolder {
		public TextView username;
		public ImageView image;
		public TextView published;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;

		final ViewHolder holder;

		if (v == null) {
			v = vi.inflate(R.layout.user_row, null);
			holder = new ViewHolder();
			holder.image = (ImageView) v.findViewById(R.id.avatar_user);
			holder.username = (TextView) v.findViewById(R.id.user);
			holder.published = (TextView) v.findViewById(R.id.published);
			v.setTag(holder);
		} else {
			holder = (ViewHolder) v.getTag();
		}

		final User user = users.get(position);
		holder.published.setText(user.getPublished() + " "
				+ getContext().getString(R.string.space_tweets));
		holder.username.setText(user.getUsername());
		imageLoader.DisplayImage(
				"https://api.twitter.com/1/users/profile_image?screen_name="
						+ user.getUsername() + "&size=normal", holder.image);

		v.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Uri uriUrl = Uri.parse("http://twitter.com/#!/"
						+ user.getUsername());
				arg0.getContext().startActivity(
						new Intent(Intent.ACTION_VIEW, uriUrl));
			}
		});

		return v;
	}

}
